#include <stdint-gcc.h>
#include <stddef.h>

#include "ucos_ii.h"

#include "timer.h"
#include "uart.h"
#include "ethmac.h"

#define TASK_STACK_SIZE 256

OS_STK task_main_stack[TASK_STACK_SIZE];
#if 0
OS_STK task11_stack[TASK_STACK_SIZE];
OS_STK task12_stack[TASK_STACK_SIZE];
OS_STK task13_stack[TASK_STACK_SIZE];
#endif

/* 参见 os_cpu_a.s */
void C_IRQHandler(void)
{
	if (timer_irq) {
		timer_irq = 0;
		// 通知μC/OS更新时钟
		OSTimeTick();
	}
	if (ethmac_intsrc) {
		ethmac_interrupt();
	}
}

#if 0
void task11(void *unused)
{
	for (;;) {
		puts("task11\r");
		OSTimeDly(100);
	}
}

void task12(void *unused)
{
	for (;;) {
		puts("task12\r");
		OSTimeDly(100);
	}
}

void task13(void *unused)
{
	for (;;) {
		puts("task13\r");
		OSTimeDly(100);
	}
}
#endif

#if 0
static uint8_t arp_packet[] = {
	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x40, 0x8d,
	0x5c, 0x7b, 0x8b, 0x0d, 0x08, 0x06, 0x00, 0x01,
	0x08, 0x00, 0x06, 0x04, 0x00, 0x01, 0x40, 0x8d,
	0x5c, 0x7b, 0x8b, 0x0d, 0xc0, 0xa8, 0x01, 0x80,
	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xa8,
	0x01, 0x11
};
#endif

void task_main(void *unused)
{
	init_ethmac();

#if 0
	OSTaskCreate(task11, 0, task11_stack + TASK_STACK_SIZE, 16);
	OSTaskCreate(task12, 0, task12_stack + TASK_STACK_SIZE, 16);
	OSTaskCreate(task13, 0, task13_stack + TASK_STACK_SIZE, 16);
#endif

	// 开启计时器
	timer_reload = 999999; // 每秒100次中断 @ 100MHz
	timer_en = 1;

	asm("cpsie i");

	for (;;) {
		puts("task_main\r");
		OSTimeDly(100);
	}
}

void main(void)
{
	// 设置UART
	uart_lcr = 0x83;
	uart_dl  = 54; /* 115200 @ 100MHz */
	uart_lcr = 0x03;

	//puts("OSInit()\r");
	OSInit();
	//puts("OSTaskCreate()\r");
	OSTaskCreate(task_main, 0, task_main_stack + TASK_STACK_SIZE, 16);

	//puts("OSStart()\r");
	OSStart();
}

void OSTaskReturnHook(OS_TCB *ptcb)
{
}
